<?php

namespace falcon5\inc\Http\Views;

trait JsonViewTrait
{
    /**
     * 发送JSON响应
     * @param mixed $data
     */
    public static function toJson($data = null)
    {
        wp_send_json($data);
    }

    /**
     * 发送JSONP响应
     * @param string|null $callback 回调函数名
     * @param array $data 要发送的数据
     */
    public static function toJsonP($callback = null, array $data = [])
    {
        if (empty($callback)) {
            $callback = isset($_GET['callback']) ? sanitize_text_field($_GET['callback']) : 'callback';
        }
        
        header('Content-Type: application/javascript');
        echo $callback . '(' . wp_json_encode($data) . ');';
        exit;
    }

    /**
     * 发送成功响应
     * @param array $data
     */
    public static function success(array $data = [])
    {
        $result = [
            'code' => 1,
            'data' => $data,
            'msg' => 'success'
        ];
        wp_send_json_success($result);
    }

    /**
     * 发送错误响应
     * @param int $code
     * @param string $msg
     * @param array|null $extra
     * @param array|null $data
     */
    public static function error(int $code = 0, string $msg = 'error', array $extra = null, array $data = null)
    {
        $result = [
            'code' => $code,
            'data' => $data,
            'msg' => $msg,
            'extra' => $extra
        ];
        wp_send_json_error($result);
    }
}